package cn.springcloud.fix.gateway.controller;

import cn.springcloud.fix.gateway.api.request.GatewayRouteAddRequest;
import cn.springcloud.fix.gateway.api.request.GatewayRouteUpdateRequest;
import cn.springcloud.fix.gateway.dao.entity.GatewayRoute;
import cn.springcloud.fix.gateway.service.RoutesService;
import com.alibaba.fastjson.JSON;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cloud.gateway.route.RouteDefinitionLocator;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;

import java.util.List;

@Controller
@RequestMapping("/gateway-routes")
public class GatewayRoutesController {

    @Autowired
    private RoutesService routesService;

    @Autowired
    private RouteDefinitionLocator routeDefinitionLocator;

    /**
     * 获取所有动态路由信息
     */
    @GetMapping("/routes")
    public String getRouteDefinitions() {
        return JSON.toJSONString(routesService.getRouteDefinitions());
    }

    @GetMapping("/list")
    public String list(Model model) {
        List<GatewayRoute> routes = routesService.getRoutes();
        model.addAttribute("list", routes);
        return "routelist";
    }

    @GetMapping("/delete")
    public String delete(Long id) {
        routesService.delete(id);
        return "delSuccess";
    }

    @GetMapping("/addRoutePage")
    public String addRoute(Model model) {
        model.addAttribute("route", new GatewayRoute());
        return "addRoute";
    }

    @GetMapping(value = "/editRoutePage")
    public String edit(Model model, Long id) {
        GatewayRoute route = routesService.getGatewayRouteById(id);
        model.addAttribute("route", route);
        return "addRoute";
    }

    @PostMapping(value = "/add")
    @ResponseBody
    public String add(@RequestBody GatewayRouteAddRequest request) {
        return routesService.addRoute(request) > 0 ? "success" : "fail";
    }

    @PostMapping(value = "/edit")
    @ResponseBody
    public String edit(@RequestBody GatewayRouteUpdateRequest request) {
        return routesService.updateRoute(request) > 0 ? "success" : "fail";
    }
}
